package com.example.portlocalforward.service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.portlocalforward.controller.model.TagRequest;
import com.example.portlocalforward.controller.model.TagResponse;
import com.example.portlocalforward.entity.Tag;
import com.example.portlocalforward.repository.TagRepository;

import lombok.extern.slf4j.Slf4j;

/**
 * 标签服务类
 * 负责管理标签信息
 * 
 * @author Generated
 * @version 1.0.0
 */
@Slf4j
@Service
@Transactional
public class TagService {

    @Autowired
    private TagRepository tagRepository;

    /**
     * 创建标签
     * 
     * @param tagRequest 标签请求信息
     * @return 创建的标签响应信息
     */
    @Transactional(rollbackFor = Exception.class)
    public TagResponse createTag(TagRequest tagRequest) {
        log.info("创建标签: {}", tagRequest.getName());
        
        // 检查标签名称是否已存在
        if (tagRepository.findByName(tagRequest.getName()).isPresent()) {
            throw new RuntimeException("标签名称已存在: " + tagRequest.getName());
        }
        
        Tag tag = new Tag();
        BeanUtils.copyProperties(tagRequest, tag);
        
        Tag savedTag = tagRepository.save(tag);
        return convertToResponse(savedTag);
    }

    /**
     * 根据ID获取标签
     * 
     * @param id 标签ID
     * @return 标签响应信息
     */
    @Transactional(readOnly = true)
    public Optional<TagResponse> getTagById(Long id) {
        log.info("根据ID获取标签: {}", id);
        return tagRepository.findById(id).map(this::convertToResponse);
    }

    /**
     * 获取所有标签
     * 
     * @return 标签列表
     */
    @Transactional(readOnly = true)
    public List<TagResponse> getAllTags() {
        log.info("获取所有标签，按照创建时间倒序");
        return tagRepository.findAll(Sort.by(Sort.Direction.DESC, "createdTime")).stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    /**
     * 更新标签信息
     * 
     * @param id 标签ID
     * @param tagRequest 标签请求信息
     * @return 更新后的标签响应信息
     */
    @Transactional(rollbackFor = Exception.class)
    public TagResponse updateTag(Long id, TagRequest tagRequest) {
        log.info("更新标签: {}", id);
        
        // 检查标签是否存在
        Optional<Tag> existingTagOpt = tagRepository.findById(id);
        if (!existingTagOpt.isPresent()) {
            throw new RuntimeException("标签不存在，ID: " + id);
        }
        
        // 检查标签名称是否被其他标签使用
        Optional<Tag> tagWithSameName = tagRepository.findByName(tagRequest.getName());
        if (tagWithSameName.isPresent() && !tagWithSameName.get().getId().equals(id)) {
            throw new RuntimeException("标签名称已被其他标签使用: " + tagRequest.getName());
        }
        
        Tag existingTag = existingTagOpt.get();
        
        // 只更新业务字段，保留时间字段
        existingTag.setName(tagRequest.getName());
        
        Tag updatedTag = tagRepository.save(existingTag);
        return convertToResponse(updatedTag);
    }

    /**
     * 删除标签
     * 
     * @param id 标签ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteTag(Long id) {
        log.info("删除标签: {}", id);
        if (!tagRepository.existsById(id)) {
            throw new RuntimeException("标签不存在，ID: " + id);
        }
        tagRepository.deleteById(id);
    }

    /**
     * 将实体转换为响应对象
     * 
     * @param tag 实体对象
     * @return 响应对象
     */
    private TagResponse convertToResponse(Tag tag) {
        TagResponse response = new TagResponse();
        BeanUtils.copyProperties(tag, response);
        return response;
    }
}

